package org.mozhu.mboot.core.config.database;

import com.ulisesbocchio.jasyptspringboot.EncryptablePropertySource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;

public class DatabasePropertySourceBeanFactoryPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered {

    private ConfigurableEnvironment configurableEnvironment;

    public DatabasePropertySourceBeanFactoryPostProcessor(ConfigurableEnvironment configurableEnvironment) {
        this.configurableEnvironment = configurableEnvironment;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        PropertySource propertySource = this.configurableEnvironment.getPropertySources().get("databaseProperties");
        if (propertySource instanceof DatabasePropertySource) {
            DatabasePropertySource databasePropertySource = (DatabasePropertySource) propertySource;
            databasePropertySource.init();
        } else if (propertySource instanceof EncryptablePropertySource) {
            EncryptablePropertySource encryptablePropertySource = (EncryptablePropertySource) propertySource;
            PropertySource delegate = encryptablePropertySource.getDelegate();
            if (delegate instanceof DatabasePropertySource) {
                DatabasePropertySource databasePropertySource = (DatabasePropertySource) delegate;
                databasePropertySource.init();
            }
        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
